package com.etone.autotesting.dao.impl;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;

import com.etone.app.support.result.JsonResult;
import com.etone.autotesting.support.PService;
import com.etone.autotesting.util.ClassUtil;
import com.etone.ejb.security.common.WsAuthenticate;

public class ConditionSearchDao {

	protected static Logger logger = Logger.getLogger(ConditionSearchDao.class);

	private static ConditionSearchDao instance = null;

	public static ConditionSearchDao getInstance() {
		if (instance == null)
			instance = new ConditionSearchDao();
		return instance;
	}

	/**
	 * 
	 * @param page
	 * @param filter
	 * @param order
	 * @param SearchService
	 * @param SearchMethod
	 * @return
	 * @throws Exception 
	 */
	public JsonResult ServiceSearchData(String page, String filter, String order, String SearchService, String SearchMethod,String serviceInfo) throws Exception {
		/*
		 * logger.info("SearchService：" + SearchService);
		 * logger.info("SearchMethod：" + SearchMethod); logger.info("page：" +
		 * page); logger.info("filter：" + filter); logger.info("order：" +
		 * order);
		 */
		JsonResult actualResult = null;
		PService service = null;
		Class clazz = null;
		try {
			clazz = ClassUtil.getSearchClass(SearchService);
			if (clazz == null) {				
				throw new Exception("没有找到相应的服务名！");				
			}
			service = new PService(clazz,serviceInfo);
			Object obj = service.getService(clazz);
			SearchMethod = convertStringFirstLower(SearchMethod);
			Method method = clazz.getDeclaredMethod(SearchMethod, WsAuthenticate.class, String.class, String.class, String.class);
			actualResult = (JsonResult) method.invoke(obj, null, page, filter, order);
		} catch (Exception ex) {
			throw new Exception(ex.getMessage());
		} finally {
			service = null;
			clazz = null;
		}		
		return actualResult;
	}

	/**
	 * 把第一个字母转换成小写
	 * 
	 * @param str
	 * @return
	 */
	private String convertStringFirstLower(String str) {
		char oldChar = str.charAt(0);
		char newChar = 'G';
		if (oldChar >= 'A' && oldChar <= 'Z')
			newChar = (char) (oldChar - 'A' + 'a');
		return str.replaceFirst(String.valueOf(oldChar), String.valueOf(newChar));
	}
}
